package com.bigevent.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.bigevent.mapper.ArticleMapper;
import com.bigevent.pojo.Article;
import com.bigevent.pojo.PageBean;
import com.bigevent.service.ArticleService;
import com.bigevent.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;
    @Override
    public void addArticle(Article article) {
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        article.setCreateUser(userId);
        articleMapper.addArticle(article);
    }

    @Override
    public PageBean<Article> getArticleList(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        //1.创建PageBean对象
        PageBean<Article> articlePageBean = new PageBean<>();
        //2.开启分页查询
        PageHelper.startPage(pageNum,pageSize);
        //3.调用mapper查询
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<Article> articles = articleMapper.getArticleList(userId,categoryId,state);
        //Page中提供了方法，可以获取PageHelper分页查询后 得到总记录条数和当前页数据
        //PageHelper 在执行分页查询时，会将查询结果包装为 Page 类型的对象。
        // 此时，虽然返回值声明为 List<Article>，但实际上运行时类型是 Page<Article>。
        // 因此，可以通过强制转换将 articles 转换为 Page<Article> 类型。
        Page<Article> page = (Page<Article>) articles;
        //4.将数据填充到PageBean对象中
        articlePageBean.setTotal(page.getTotal());
        articlePageBean.setItems(page.getResult());//当前页的数据集合
        return articlePageBean;
    }

    @Override
    public Article articleDetail(Integer id) {
        return articleMapper.articleDetail(id);
    }

    @Override
    public void updateArticle(Article article) {
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.updateArticle(article);
    }

    @Override
    public void deleteArticle(Integer id) {
        articleMapper.deleteArticle(id);
    }
}
